package com.example.androidproject.activity.utils;





import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.RequiresApi;


import java.util.*;
import java.util.stream.Collectors;

/**
 * 签名的生成规则类
 *
 * @date 2023/2/29 16:08
 */
public class SignRule {
    /**
     *  POST请求
     * @param url  请求路径
     * @param secretKey  生成的secret
     * @param bodys  请求体
     * @param headers 请求头
     * @return
     * @throws Exception
     */

   /* public  String postSign(String method,String url, String secretKey, String bodys, TreeMap<String, String> headers) {
        String sign = sign(method.toUpperCase(), url, secretKey, bodys, headers);
        return sign;
    }*/


    /**
     *  GET 请求
     * @param url 请求路径
     * @param secretKey 生成的secret
     * @param headers  请求头
     * @return
     * @throws Exception
     */

    public  String getSignData( String method,String url,
                           String secretKey,String bodys,  TreeMap<String, String> headers){
        String sign = sign(method, url, secretKey, bodys, headers);
        return sign;
    }
    /**
     * 生成secret
     *
     * @param secret32      32固定长度字符
     * @param secret36      36位动态调整字符
     * @param timeStamp     请求时间戳
     * @param deviceId      设备id
     * @param authorization 登录token
     * @return {@link String}
     * @throws
     * @date 2023/1/29 18:40
     */
    public  String getSecret(String secret32, String secret36, Long timeStamp, String deviceId, String authorization) {
        if ((secret32!=null&&secret32.trim().length()<32) || (secret36!=null&&secret36.trim().length()<36)){
            return  "";
        }
        //符合起始位置
        String subTimeStamp = String.valueOf(timeStamp);
        String subNoteIndex = "";
        if (subTimeStamp.trim().length()>=5){
            subNoteIndex = subTimeStamp.substring(subTimeStamp.length() - 5);
        }
        //读取起始位置
        int noteIndex = Integer.parseInt(subNoteIndex) % 32;

        //时间戳与2其余 0横读1竖读
        long redadType = timeStamp % 2;
        Long deviceIndex = timeStamp % 8;
        String subToken = "";
       // Log.i("bindXingeToken", "getSecert: timeStamp: "+timeStamp+",authorization.length()>9:"+authorization.length()+",authorization:"+authorization);

        if (authorization!= null  && !authorization.trim().equals("")&&authorization.trim().length()>9){
            subToken = authorization.substring(3, 9);
        }

        String devices = "";
        try {
           devices =  isNotEmpty(deviceId) ? deviceId.substring(deviceIndex.intValue(), deviceIndex.intValue() + 6) : "";
        }catch (Exception e){
            devices ="";
        }
       // String devices = deviceId.substring(deviceIndex.intValue(), deviceIndex.intValue() + 6);
        String secert = null;
        //1竖着读
        if (redadType == 1) {
            //竖着6个字符数据组收尾相接
            char[] chars = secret36.toCharArray();

            //己维度数组-正矩阵
            int weidu = 6;
            List<List<String>> erList = new ArrayList<>();
            List<String> ywList = new ArrayList<>();
            for (int i = 0; i < chars.length; i++) {
                ywList.add(String.valueOf(chars[i]));
                if ((i + 1) % weidu == 0) {
                    erList.add(ywList);
                    ywList = new ArrayList<>();
                }
            }

            //每个集合中取出相同位置的元素拼接字符串
            StringBuilder svb = new StringBuilder();
            for (int i = 0; i < weidu; i++) {
                for (int j = 0; j < weidu; j++) {
                    svb.append(erList.get(j).get(i));
                }
            }
            while (noteIndex + 6 > svb.length()) {
                svb.append(svb);
            }

            String stsx = svb.substring(noteIndex, noteIndex + 6);
            secert = secret32 + stsx;
        } else {
            while (noteIndex + 6 > secret36.length()) {
                secret36 += secret36;
            }
            secert = secret32 + secret36.substring(noteIndex, noteIndex + 6);
        }

        return secert + devices + subToken;
    }

    /**
     * 生成sign
     *
     * @param method    方法
     * @param url       请求路径
     * @param secret    this.getSecert方法生成的
     * @param body      post参数体
     * @param headers   请求头
     * @return {@link String}
     * @throws
     * @date 2023/1/29 18:40
     */
    private String sign(String method, String url,
                           String secret, String body, TreeMap<String, String> headers
                           )  {


        StringBuilder signStr = new StringBuilder();
        signStr.append(method.toUpperCase()).append(url);

        for (Map.Entry<String, String> header : headers.entrySet()) {
            signStr.append(header.getKey().toLowerCase()).append(":").append(header.getValue());
        }

        if ("POST".equals(method.toUpperCase())) {
            signStr.append("json="+(isNotEmpty(body)?body:""));
        }

      /*  //拼装param
        TreeMap<String, String> sortParameterMap = new TreeMap<>();
        if (null != params) {
            sortParameterMap.putAll(params);
        }
        for (Map.Entry<String, String> parameter : sortParameterMap.entrySet()) {
            signStr.append(parameter.getKey().toLowerCase()).append("=").append(parameter.getValue());
        }*/

        signStr.append(secret);
        Log.i("YFFSD", "sign: signStr: "+signStr);
        // 生成签名
        String sign = Sha256Util.encryption(signStr.toString());
        return sign;
    }


    public  String signTest(String method, String url,
                             String secret, String body, TreeMap<String, String> headers)
                              {

        headers.remove("Sign");

        // 拼接
        StringBuilder signStr = new StringBuilder();
        signStr.append(method.toUpperCase()).append(url);
        for (Map.Entry<String, String> header : headers.entrySet()) {
            signStr.append(header.getKey().toLowerCase()).append(":").append(header.getValue());
        }

      if ("POST".equals(method.toUpperCase())) {
        signStr.append("json="+(isNotEmpty(body)?body:""));
      }
       signStr.append(secret);
      //  Log.i("TAGinterceptor", "获取签名 url: "+url+",sign: "+signStr);

        return signStr.toString();
    }

    private  boolean isNotEmpty(String str) {
        return str != null;
    }

}
